// pages/myPromoter/index.js
const userUtils = require("../../utils/user");
const validate = require('../../utils/validate');
const common = require('../../utils/common');
const wxp = require('../../utils/wxp.js');
const {
  getPromoterShopStats
} = require('../../services/promoter');
const defaultPage = {
  curPage: 1,
  pageSize: 10,
  noMore: false
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    shopInfo: {},
    query: {
      ...defaultPage
    },
    pInfo: {},
    promoterList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu({});
    // 初始化数据
    this.initData(options);
    // 获取数据
    this.onPullDownRefresh();
  },

  // 初始化数据
  initData(options) {
    let data = common.jsonParse(options.optionsData);
    this.setData({
      shopInfo: data
    });
    // 设置title
    if (data.navTitle) {
      wx.setNavigationBarTitle({
        title: data.navTitle,
      })
    }
  },

  // 获取我的店铺信息
  requestTogGetPromoterShopStats({
    curPage,
    pageSize
  }, pullDownRefresh) {
    let params = {
      curPage: curPage,
      pageSize: pageSize,
      shopId: this.data.shopInfo.shopId
    }
    getPromoterShopStats(params).then(res => {
      if (pullDownRefresh) {
        wx.stopPullDownRefresh({});
      }
      this.hanlePromoterShopStatsData(res, curPage, pullDownRefresh);
    }).catch(err => {
      if (pullDownRefresh) {
        wx.stopPullDownRefresh({});
      }
      common.log(err);
    })
  },

  // 处理返回的数据
  hanlePromoterShopStatsData(res, curPage, pullDownRefresh) {
    //设置数据
    var tmpList = this.data.promoterList;
    if (pullDownRefresh) {
      tmpList = [];
    }
    //pageInfo
    var tmpPageInfo = this.data.query;
    if (res.page.pages <= curPage) {
      tmpPageInfo.noMore = true;
    } else {
      tmpPageInfo.curPage++;
    }
    //list
    if (res.data.length > 0) {
      tmpList = [...tmpList, ...res.data];
    }
    this.setData({
      query: tmpPageInfo,
      pInfo: res.page,
      promoterList: tmpList
    });
  },
  queryChange: function (payload, pullDownRefresh) {
    this.setData({
      query: {
        ...this.data.query,
        ...payload
      }
    });
    this.requestTogGetPromoterShopStats(this.data.query, pullDownRefresh);
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.queryChange(defaultPage, true);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.query.noMore) return;
    this.queryChange(this.data.query);
  },
})
